
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jl_plugin/bean/BlueDevice.dart';
import 'package:jl_plugin/jl_plugin.dart';
import 'package:jl_plugin_example/AppBarLeftTitle.dart';
import 'package:jl_plugin_example/main.dart';
import 'package:jl_plugin_example/widget/MyTextField.dart';
import 'package:jl_plugin_example/widget/TextUtils.dart';

class BlueCmdPage extends StatefulWidget{
  BlueDevice blueDevice;

  BlueCmdPage(this.blueDevice);
  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends State<BlueCmdPage>{
  TextEditingController textEditingController=TextEditingController();
  List<String> respList=[];

  
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarLeftTitle(title: "自定义指令"),
      backgroundColor: Color(0xfff0f0f0),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(15),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              height: 100,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey,width: 1)
              ),
              child: MyTextField(
                controller: textEditingController,
                hintText: "指令",
              ),
            ),
            SizedBox(height: 10),
            Row(mainAxisAlignment: MainAxisAlignment.end,children: [
              TextButton(onPressed: (){
              }, child: Text("清空")),

              SizedBox(width: 10),
              TextButton(onPressed: (){
                var cmdTxt = textEditingController.text;
                if(TextUtils.isNotEmpty(cmdTxt)){
                  sendCmdData(cmdTxt);
                }
              }, child: Text("发送指令")),
            ],),

            Expanded(child: ListView.builder(itemBuilder: (context,index){
              return Text("${respList[index]}");
            },itemCount: respList.length,))
          ],
        ),
      ),
    );
  }
  
  void sendCmdData(String data){
    JlPlugin.instance.sendCmd( data);
  }

  late JlDeviceCommandCallBack cmdReceive;
  
  @override
  void initState() {
    super.initState();
    cmdReceive=(int type,String hex,Uint8List bytes){
      print("cmdReceive:type:${type}--hex:${hex}");
      setState(() {
        respList.add("接受到的数据：${hex}");
      });
    };
    JlPlugin.instance.addCommandCmdCallback(cmdReceive);
    startService();
  }

  @override
  void dispose() {
    super.dispose();
    JlPlugin.instance.removeCommandCmdCallback(cmdReceive);
  }

}